from game_object_base import *
import os.path
import pygame

class base(game_object_base):
    def __init__(self, game, config_file):
        self.game = game
        self.game_logic = game.game_logic
        self._cfg = {}
        self._load_config(config_file)
        src_file = os.path.join(*self._cfg['image'])
        if not os.path.isfile(src_file):
            pygame.event.post(pygame.event.Event(pygame.QUIT))
            print "file not found: %s" % src_file
            return
        source_img = pygame.image.load(src_file)
        self.image = pygame.Surface((int(self._cfg['rect'][2]), int(self._cfg['rect'][3])))
        self.image.set_colorkey((255, 0, 255))
        self.image.blit(source_img, source_img.get_rect(), pygame.Rect(int(self._cfg['rect'][0]), int(self._cfg['rect'][1]), int(self._cfg['rect'][2]), int(self._cfg['rect'][3])))
        self.rect = self.image.get_rect()
        
        #count frames
        self.ammo_count = 0
        self.health_count = 0
    
    def _load_config(self, config_file):
        f = open(config_file, "r")
        lines = f.readlines()
        f.close()
        for line in lines:
            parts = line.replace("\n", "").split("=")
            self._cfg[parts[0]] = parts[1].split(";")
        
        for c in self._cfg:
            print "self._cfg['"+c+"'] == ", self._cfg[c]
            
    def update(self):
        if self.dirty:
            self.rect.x = self.posX
            self.rect.y = self.posY
            self.dirty = False
        
        if self.game.config.host:
            for p in self.game.players:
                play = self.game.players[p]
                if self.rect.colliderect(play.tank.rect) and play.tank.alive:
                    self.grant_ammo(play.tank, 20)
                    self.grant_health(play.tank, 20)
                
    def grant_ammo(self, obj, frames):
        self.ammo_count+= 1
        if self.ammo_count == frames:
            misc = {"pre_grant_ammo":obj.ammo}
            self.game.game_logic.send_user_event("grant_ammo", obj.player, misc)
            self.ammo_count = 0
                
    def grant_health(self, obj, frames):
        self.health_count+= 1
        if self.health_count == frames:
            misc = {"pre_heal_health":obj.health}
            self.game.game_logic.send_user_event("obj_heal", obj.player, misc)
            self.health_count = 0
    
    def move(self, x, y):
        self.posX = x
        self.posY = y
        self.dirty = True
